package io.github.jesse205.deskclock.lite.utils;

import android.os.Handler;
import android.os.SystemClock;

import androidx.annotation.Nullable;

/**
 * 整时、分、秒定时器
 */
public class TimeUpdateTimer {
    private static final String TAG = "TimeUpdateTimer";
    public static final long DURATION_SECOND = 1000L;
    public static final long DURATION_MINUTE = 60 * DURATION_SECOND;
    public static final long DURATION_HOUR = 60 * DURATION_MINUTE;

    @Nullable
    private OnTimeUpdateListener listener;
    private final Handler handler;
    private long duration = 1000;
    private boolean isStarted = false;
    private final Callback callback = new Callback();


    public TimeUpdateTimer(Handler handler) {
        this.handler = handler;
    }

    public void start() {
        isStarted = true;
        handler.post(callback);
    }

    public void stop() {
        isStarted = false;
        handler.removeCallbacks(callback);
    }

    public void restart() {
        stop();
        start();
    }

    public boolean isStarted() {
        return isStarted;
    }

    /**
     * 设置间隔时间
     *
     * @param duration {@code 1000L}为秒，{@code 60*1000L}为分钟，{@code 60*60*1000L}为小时，可以使用静态变量{@link #DURATION_SECOND}，{@link #DURATION_MINUTE}，{@link #DURATION_HOUR}
     */
    public void setDuration(long duration) {
        this.duration = duration;
    }

    public void setOnTimeUpdateListener(@Nullable OnTimeUpdateListener listener) {
        this.listener = listener;
    }

    private void postAtNextTime(long currentTimeMillis) {
        long timeMillisOffset = currentTimeMillis % duration;
        long uptimeMillis = SystemClock.uptimeMillis();
        handler.postAtTime(callback, uptimeMillis + duration - timeMillisOffset);
    }

    private final class Callback implements Runnable {

        @Override
        public void run() {
            long timeMillis = System.currentTimeMillis();
            postAtNextTime(timeMillis);
            if (listener != null) {
                listener.onTimeUpdate(timeMillis);
            }
        }
    }


    public interface OnTimeUpdateListener {
        void onTimeUpdate(long timeMillis);
    }
}
